//
//  CJRequestManager.m
//  DatangLife
//
//  Created by 娜 on 2018/4/18.
//  Copyright © 2018年 DatangLife. All rights reserved.
//

#import "CJRequestManager.h"


@interface AFHTTPSessionManager (Shared)
// 设置为单利
+ (instancetype)sharedManager;
@end

@implementation AFHTTPSessionManager (Shared)
+ (instancetype)sharedManager {
    static AFHTTPSessionManager *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [AFHTTPSessionManager manager];
//        _instance.requestSerializer = [AFJSONRequestSerializer serializer];
       _instance.requestSerializer.timeoutInterval = 10.f;
       _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain", @"text/json", @"text/javascript", @"text/html", nil];
 
    });
    return _instance;
}
@end

@implementation CJRequestManager


+ (BOOL)netWorkReachabilityWithURLString:(NSString *)strUrl{
    __block BOOL netState = NO;
    NSURL *baseURL = [NSURL URLWithString:strUrl];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    NSOperationQueue *operationQueue = manager.operationQueue;
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];//恢复队列
                netState = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                netState = NO;
                break;
            default:
                [operationQueue setSuspended:YES];//暂停队列
                break;
        }
    }];
    [manager.reachabilityManager startMonitoring];//启动监听
    return netState;
}

// GET请求
+ (void)GET:(NSString *)URLString
 parameters:(id)parameters
responseSeializerType:(CJResponseSeializerType)type
    success:(void (^)(id))success
    failure:(void (^)(NSError *))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager sharedManager];
   
    

//     如果不是JSON 或者 不是Default 才设置解析器类型
    if (type != CJResponseSeializerTypeJSON && type != CJResponseSeializerTypeDefault) {
         manager.responseSerializer = [self responseSearalizerWithSerilizerType:type];
    }
    
    // https证书设置
    
//     AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//     policy.allowInvalidCertificates = YES;
//     manager.securityPolicy  = policy;
     
    [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *resultDic = [self toArrayOrNSDictionary:responseObject];
        NSLog(@"%@",resultDic);
        NSInteger code = [resultDic[@"code"] integerValue];
        if (code == 200) {
            if (success) {
                success(resultDic);
            }
        }else{
            
            [CJUIKit showErrorWithStatus:resultDic[@"msg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        // 失败
        if (failure) {
            failure(error);
        }
        
    }];
}

// POST请求
+ (void)POST:(NSString *)URLString
  parameters:(id)parameters
responseSeializerType:(CJResponseSeializerType)type
     success:(void (^)(id))success
     failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager sharedManager];

   

    //     如果不是JSON 或者 不是Default 才设置解析器类型
    if (type != CJResponseSeializerTypeJSON && type != CJResponseSeializerTypeDefault) {
        manager.responseSerializer = [self responseSearalizerWithSerilizerType:type];
    }
    //  https证书设置
    
//    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//    policy.allowInvalidCertificates = YES;
//    manager.securityPolicy  = policy;
    
    
    [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        NSDictionary *resultDic = [self toArrayOrNSDictionary:responseObject];
        NSLog(@"%@",resultDic);
        if ([resultDic[@"Success"] intValue] == 1) {
            if (success) {
                success(resultDic);
            }
        }else{
            NSLog(@"%@",resultDic[@"ErrorDesc"]);
            [CJUIKit showErrorWithStatus:resultDic[@"msg"]];
        }
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //        [MBProgressHUD hideAllHUDsInView:nil];
        //
        //        [MBProgressHUD showMessage:@"网络失败~请重新再试" toView:nil];
        // 失败
        NSLog(@"%@",error);
        if (failure) {
            failure(error);
        }
    }];
}
+ (NSDictionary *)toArrayOrNSDictionary:(NSData *)jsonData{

    NSLog(@"%@",jsonData);
    NSString * str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString * str2 = [str stringByReplacingOccurrencesOfString:@"\t" withString:@""];

    str2 = [str2 stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    str2 = [str2 stringByReplacingOccurrencesOfString:@"\r" withString:@""];

    str2 = [str2 stringByReplacingOccurrencesOfString:@"//" withString:@"/"];

    NSLog(@"%@",str2);
    if ([str2 hasPrefix:@"{"]) {
        NSLog(@"==");
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[str2 dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        return dict;
    }else{
        // { 这前边有隐藏的字符 不然会出现 3840
        NSRange range = [str2 rangeOfString:@"{"];
        NSLog(@"==%ld==",range.location);
        NSString *str3 = [str2 substringFromIndex:range.location];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[str3 dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        return dict;
    }
    
    
}

// POST请求 上传数据
+ (void)POST:(NSString *)URLString
  parameters:(id)parameters
responseSeializerType:(CJResponseSeializerType)type
constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block
     success:(void (^)(id))success
     failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager sharedManager];
    
    // 请求头
    //    NSString *value = [NSString stringWithFormat:@"Bearer %@",[ CommonTool validStringWithObj:kUserInfo[@"token"]]];
    //    if (value) {
    //        [manager.requestSerializer setValue:value forHTTPHeaderField:@"Authorization"];
    //    }
    // 如果不是JSON 或者 不是Default 才设置解析器类型
    if (type != CJResponseSeializerTypeJSON && type != CJResponseSeializerTypeDefault) {
        manager.responseSerializer = [self responseSearalizerWithSerilizerType:type];
    }
    // https证书设置
    /*
     AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
     policy.allowInvalidCertificates = YES;
     manager.securityPolicy  = policy;
     */
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (block) {
            block(formData);
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *resultDic = [self toArrayOrNSDictionary:responseObject];
        NSLog(@"%@",resultDic);
        if ([resultDic[@"Success"] intValue] == 1) {
            if (success) {
                success(resultDic);
            }
        }else{
            NSLog(@"%@",resultDic[@"ErrorDesc"]);
            [CJUIKit showErrorWithStatus:resultDic[@"msg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //        [MBProgressHUD showMessage:@"网络出错" toView:[UIApplication sharedApplication].keyWindow];
        NSLog(@"%@", error);
        if (failure) {
            failure(error);
        }
        
    }];
}

/**
 *  设置数据解析器类型
 *  @param manager       请求管理类
 *  @param serilizerType 数据解析器类型
 */
+ (AFHTTPResponseSerializer *)responseSearalizerWithSerilizerType:(CJResponseSeializerType)serilizerType {
    
    switch (serilizerType) {
            
        case CJResponseSeializerTypeDefault: // default is JSON
            return [AFJSONResponseSerializer serializer];
            break;
            
        case CJResponseSeializerTypeJSON: // JSON
            return [AFJSONResponseSerializer serializer];
            break;
            
        case CJResponseSeializerTypeXML: // XML
            return [AFXMLParserResponseSerializer serializer];
            break;
            
        case CJResponseSeializerTypePlist: // Plist
            return [AFPropertyListResponseSerializer serializer];
            break;
            
        case CJResponseSeializerTypeCompound: // Compound
            return [AFCompoundResponseSerializer serializer];
            break;
            
        case CJResponseSeializerTypeImage: // Image
            return [AFImageResponseSerializer serializer];
            break;
            
        case CJResponseSeializerTypeData: // Data
            return [AFHTTPResponseSerializer serializer];
            break;
            
        default:  // 默认解析器为 JSON解析
            return [AFJSONResponseSerializer serializer];
            break;
    }
}

+ (void)cancelAllRequests {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager sharedManager];
    [manager.operationQueue cancelAllOperations];
}
@end
